package com.gen.generator.actions;

import com.gen.generator.config.CodeGenConfig;
import com.gen.generator.service.CodeGenerator;
import com.gen.generator.ui.RightCodeGenDialog;
import com.gen.generator.util.DBUtil;
import com.gen.generator.util.ErrorUtil;
import com.intellij.database.psi.DbTable;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.ui.Messages;

import javax.swing.*;

public class RightGenerateCodeAction extends AnAction {


    @Override
    public void actionPerformed(AnActionEvent e) {
        try {
            var element = e.getData(CommonDataKeys.PSI_ELEMENT);
            if (!(element instanceof DbTable table)) {
                Messages.showMessageDialog("未选择数据库表", "提示", Messages.getWarningIcon());
                return;
            }
            // 弹出对话框
            RightCodeGenDialog dialog = new RightCodeGenDialog(e.getProject());
            if (dialog.showAndGet()) {
                CodeGenConfig config = DBUtil.getConfig(table, dialog);
                CodeGenerator.genCode(config);
                JOptionPane.showMessageDialog(null, "代码生成成功！");
            }
        }catch (Exception ex){
            ErrorUtil.showError(ex,null);
        }
    }
}
